<?php

class ApiController extends Controller_Base
{

    public static function mediate_outnumber(){
        $callPass = Yaf_Registry::get("config")->callPass;
        return Module_Mediate_ClientsTels::ClientsToNum($callPass);
    }
    public function init()
    {
        $postData = file_get_contents("php://input");//这样也可以获取
        $postData = json_decode($postData, 1);
        if (empty($postData['randkey'])) {
            $this->_returnJson(500, [], '缺少请求参数');
        }
        $randkey = $postData['randkey'];
        unset($postData['randkey']);

        if ($this->encryptMD5($postData) != $randkey) {
            $this->_returnJson(500, [], '非法请求');
        }
    }

    /**
     * 通过身份证 查询 案件信息
     * @throws Exception
     */
    public function indexAction()
    {
        $postData = file_get_contents("php://input");//这样也可以获取
        $postData = json_decode($postData, 1);
        $card_id = $postData['card_id'];
        $mobile = $postData['mobile'];
        $type = $postData['type'];
        $is_log = $postData['is_log'];
        if (empty($card_id)) {
            $this->_returnJson(400, [], '缺少身份证号/案件验证码');
        }
        if (!empty($card_id)) {
            if(is_numeric($card_id) && strlen($card_id) == 6){//如果都是数字，6位为验证码
                 //验证码
                $codeCase = Module_Mediate_CaseCode::getInstance()->getCaseId($card_id);
                $list = empty($codeCase) ? [] : [$codeCase];
            }else{
                $search = [
                    'where' => ["card_id='{$card_id}'"]
                ];
                $list = Module_Mediate_CaseRespondents::getInstance()->getAllBySearch([], $search);
            }
        }
        $redis_key = 'search_count_index';

        $old_case_id = $caseinfo = $case_id_arr = [];
        $iscreat = 0;
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                if (in_array($v['case_id'], $old_case_id)) {
                    //一个身份证号 可以查到 多个 通一个案件,
                    continue;
                }
                $case = Module_Mediate_Case::getInstance()->getOne([],["id = {$v['case_id']}","withdraw_status = 1 and entry_status in (1,2) and is_search=1"]);

                if(empty($case)){
                    continue;
                }
                if ($is_log) {
                    //每日 查询统计数据,后面有定时脚本 去修改cases表 search_count 字段
                    Lib_Redis_Hash::hIncrby($redis_key, $v['case_id'], 1);
                    $post_data = [
                        'type' => 'Module_Task_Case',
                        'method' => 'addCallMibile',
                        'data' => [
                            'case_id' => $v['case_id'],
                            'call_mobile' => $mobile,
                            'type' => 5,
                        ],
                    ];
                    @Module_Queue_Base::addQueue($post_data);
                    if($iscreat == 0){
                        $post_data = [
                            'type' => 'Module_Task_Case',
                            'method' => 'creatWorkerOrder',
                            'data' => [
                                'case_id' => $v['case_id'],
                                'mobile' => $mobile,
                                'search_type' => $type ?? 0,
                            ],
                        ];
                        @Module_Queue_Base::addQueue($post_data);
                        $iscreat == 1;
                    }
                }
                $case_code = Module_Mediate_CaseCode::getInstance()->getOne([], ["case_id='{$v['case_id']}' order by id desc"]);
                $mediate_outnumber = '';
                $admin = Module_User_Administrator::getInstance()->getItemById($case['mediator_id'], true);
                if (!empty($admin['job_number'])) {
                    $mediate_outnumber= self::mediate_outnumber()[$admin['job_number']] ?? '--';
                }
                if (!empty($case)) {
                    $case_id_arr[] = $case['id'];
                    $caseinfo[] = [
                        'id' => $case['id'],
                        'court' => !empty($case['court']) ? $case['court'] : '--',
                        'batch_num' => !empty($case['batch_num']) ? $case['batch_num'] : '--',
                        'case_source' => !empty($case['case_source']) ? $case['case_source'] : '--',
                        'mediation_code' => !empty($case['mediation_code']) ? $case['mediation_code'] : '--',
                        'code' => !empty($case_code['code']) ? $case_code['code'] : '--',
                        'case_status' => Module_Mediate_Case::$caseStatusArr[$case['case_status']],
                        'mediate_outnumber' => !empty($mediate_outnumber) ? $mediate_outnumber : '--',
                        'mediator_name' => !empty($case['mediator_name']) ? $case['mediator_name'] : '--',
                        'qkze' => !empty($case['qkze']) ? $case['qkze'] : '0',
                        'respondents' => !empty($case['respondents']) ? $case['respondents'] : '',
                        'search_mediate_step' => !empty($case['search_mediate_step']) ? $case['search_mediate_step'] : '',
                        'search_litigation_step' => !empty($case['search_litigation_step']) ? $case['search_litigation_step'] : '',
                        'platform_id' => !empty($case['platform_id']) ? $case['platform_id'] : '',
                    ];
                }
                $old_case_id[]=$v['case_id'];
            }
        }
        if ($is_log) {
            $search_log = [
                'type' => $type ?? 0,
                'mobile' => !empty($mobile) ? $mobile : (!empty($list[0]['mobile']) ? $list[0]['mobile'] : ''),
                'card_id' => !empty($card_id) ? $card_id : (!empty($list[0]['card_id']) ? $list[0]['card_id'] : ''),
                'case_id' => implode(",", $case_id_arr),
                'defendant_name' => !empty($list[0]['defendant_name']) ? $list[0]['defendant_name'] : '',
                'create_time' => time(),
            ];
            Module_Mediate_Websearchlog::getInstance()->singleInsert($search_log);
        }

        $this->_returnJson(200, $caseinfo);
    }

    /**
     * 获取 案件相关数量
     * @throws Exception
     */
    public function getCaseNumAction()
    {

        $court = Yaf_Registry::get("config")->court;
        if($court == "成都融成金融纠纷调解中心"){
            $complete_cases_num = 130 + ceil((time() - 1669305600) / ceil((86400/ceil(date("d")/3))));
            $add_cases_num = 33260 + ceil((time() - 1677168000) / 86400 * 19);;
        }elseif ($court == "成都锦城金融调解中心"){
            $complete_cases_num = 1103 + ceil((time() - 1698768000) / ceil((86400/ceil(date("d")/3))));
            $add_cases_num = 12023 + ceil((time() - 1701360000) / 86400 * 19);;
        }elseif ($court == "成都兴蓉金融纠纷调解中心"){
            $complete_cases_num = 1109 + ceil((time() - 1701360000) / ceil((86400/ceil(date("d")/3))));
            $add_cases_num = 12045 + ceil((time() - 1701360000) / 86400 * 19);;
        }else{
            $complete_cases_num = ceil((time() - 1669305600) / ceil((86400/ceil(date("d")/3))));
            $add_cases_num = ceil((time() - 1701360000) / 86400 * 19);
        }
//        $search = [
//            'where' => ["repay_status='finish_repay'"]
//        ];
//        $complete_cases_num = Module_Mediate_Case::getInstance()->getAllBySearch(['count(*) as num'], $search, true);

//        $search = [
//            'where' => []
//        ];
//        $add_cases_num = Module_Mediate_Case::getInstance()->getAllBySearch(['count(*) as num'], $search, true);
        $this->_returnJson(200, ['complete_cases_num' => $complete_cases_num, 'add_cases_num' => $add_cases_num]);

    }


    /**
     * 获取调解员信息
     */
    public function getMediatorAction()
    {
        $court = Yaf_Registry::get("config")->court;
        $search = [
            'where' => ["job_number>0","role_id <> 1"]
        ];
        if($court == "上饶金融纠纷调解委员会信州分会"){
            $clientsTels = Module_User_ClientsTels::getInstance()->getAllBySearch(['jobnum,phone_num'],['where'=>["type=1","is_delete=0"]]);
            $outnumber = array_column($clientsTels,'phone_num','jobnum');
        }else{
            $outnumber =  self::mediate_outnumber();
        }
        $list = Module_User_Administrator::getInstance()->getAllBySearch(['id', 'name', 'job_number', 'status', 'is_show_web', 'head_img', 'mobile'], $search, true);
        if (!empty($list)) {
            foreach ($list as $k => $item) {
                $list[$k]['mediate_outnumber'] = $outnumber[$item['job_number']] ?? '';
            }
        }
        $edit = array_column($list,'mediate_outnumber');
        array_multisort($edit,SORT_ASC,$list);
        $this->_returnJson(200, $list);

    }

    public function getCaseInfoAction()
    {
        $postData = file_get_contents("php://input");//这样也可以获取
        $postData = json_decode($postData, 1);
        $case_id = $postData['case_id'];
        $case = Module_Mediate_Case::getInstance()->getItemById($case_id);

        if (!empty($case)) {

            $platform = Module_InfoBase_LoanPlatform::getInstance()->getItemById($case['platform_id'], true);
            $case['platform_name'] = $platform['name'] ?? '';
            $case['company'] = $platform['company'] ?? '';
            $case['legal_name'] = $platform['legal_name'] ?? '';
            $case['credit_code'] = $platform['credit_code'] ?? '';
            $case['address'] = $platform['address'] ?? '';

            $caseCode = Module_Mediate_CaseCode::getInstance()->getItemById($case['id'], true, 'case_id');
            $case['code'] = $caseCode['code'] ?? '';
            $case['mediate_outnumber'] = '';
            $admin = Module_User_Administrator::getInstance()->getItemById($case['mediator_id'], true);
            if (!empty($admin['job_number'])) {
                $case['mediate_outnumber'] = self::mediate_outnumber()[$admin['job_number']] ?? '--';
            }

        }


        $this->_returnJson(200, $case);
    }


}